import pymongo

authType = 'SCRAM-SHA-1'


class MongoDB(object):

    def __init__(self):
        self.mongo_host = '39.107.227.235'
        self.mongo_port = 27017
        self.username = 'root'
        self.password = 'Yanhan.1218'
        self.mongo_db = 'tb_BossPosition'
        self.client = None
        self.db = None

    def open_spider(self,):
        self.client = pymongo.MongoClient(
            f'mongodb://{self.username}:{self.password}@{self.mongo_host}:{self.mongo_port}'
        )
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        # 爬虫关闭,数据库跟着关闭
        self.client.close()

    def process_item(self, item):
        # 将item数据保存在mongo中
        self.db[f'java_{item["city"]}'].insert_one(dict(item))


a = MongoDB()
a.open_spider()
a.process_item({
    'city': 'beijing',
    'message': '123'
})
